import { computed, InjectionKey, Ref } from 'vue';
import { createContext, useContext } from '/@/hooks/core/useContext';

export interface FormPermit {
  [key: string]: any;
}

const key: InjectionKey<FormPermit> = Symbol();

export function createFormPermitContext(context: FormPermit) {
  return createContext<FormPermit>(context, key);
}

export function useFormPermitContext() {
  return useContext<FormPermit>(key);
}

// 默认授权，即没有显式地设置权限：0
// 无权限：1
// 读权限：2
// 写权限：6
// 读权限（非必填）：8
// 写权限（非必填）：24
// 必填权限：56

interface PERMITMENU {
  ctrlId: string;
  ctrlBehavior: number;
}
export const useFormPermit = (codePermit: Ref<PERMITMENU[]>) => {
  const injectPermit = codePermit || useFormPermitContext();

  const isDefault = (code) => {
    if ([0].includes(code) || !code) {
      return true;
    }
  };
  const permit = computed(() => {
    return injectPermit.value.reduce((pre, cur) => {
      pre[cur.ctrlId] = cur.ctrlBehavior;
      return pre;
    }, {});
  });

  // 是否显示
  const judgeIf = (code: string, defaultVal = true) => {
    const permitCode = permit.value[`${code}`];
    if (isDefault(permitCode)) {
      return defaultVal;
    }
    if ([1].includes(permitCode)) {
      return false;
    }
    return true;
  };
  // 只读权限
  const judgeRead = (code: string, defaultVal?: boolean | undefined) => {
    const permitCode = permit.value[`${code}`];
    if (isDefault(permitCode)) {
      return defaultVal;
    }
    if (!judgeIf(code)) {
      return true;
    }
    if ([2, 8].includes(permitCode)) {
      return true;
    }
    return false;
  };
  // 必填权限
  const judeRequired = (code: string, defaultVal = false) => {
    const permitCode = permit.value[`${code}`];
    if (isDefault(permitCode)) {
      return defaultVal;
    }
    if ([56].includes(permitCode)) {
      return true;
    }
    return false;
  };
  
  const judeRequiredForNative = (code: string, defaultVal = false) => {
    const isShow = judgeIf(code, true)
    if(!isShow){
      return false
    }else{
      return judeRequired(code, defaultVal)
    }
  };
  return {
    judgeIf,
    judgeRead,
    judeRequired,
    judeRequiredForNative,
  };
};
